package cn.edu.zust.se.hellodubbo.service.impl;

import cn.edu.zust.se.hellodubbo.dao.UserDao;
import cn.edu.zust.se.hellodubbo.dto.UserDto;
import cn.edu.zust.se.hellodubbo.entity.TUser;
import cn.edu.zust.se.hellodubbo.service.UserService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@DubboService(version = "${hello.service.version}")
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Override
    public UserDto addUser(UserDto user) {
        TUser tuser=new TUser();
        BeanUtils.copyProperties(user,tuser,new String[]{"id"});
        userDao.save(tuser);
        BeanUtils.copyProperties(tuser,user);
        return user;
    }

    @Override
    public UserDto login(UserDto userDto) {
        String token= UUID.randomUUID().toString();
        TUser user=userDao.findByUsernameAndAndPassword(userDto.getUsername(),userDto.getPassword());
        UserDto u=new UserDto();
        if(user!=null){
            user.setToken(token);
            BeanUtils.copyProperties(user,u);
        }
        return u;
    }

    @Override
    public UserDto getUserById(int id) {
        TUser user=userDao.getOne(id);
        UserDto userDto=new UserDto();
        if(user!=null)
            BeanUtils.copyProperties(user,userDto);
        return userDto;
    }

    @Override
    public List<UserDto> findAll() {
        List<TUser> tusers=userDao.findAll();
        List<UserDto> userList=new ArrayList<>();
        if(tusers!=null&& tusers.size()>0){
            for(TUser u:tusers){
                UserDto userDto=new UserDto();
                BeanUtils.copyProperties(u,userDto);
                userList.add(userDto);
            }
        }
        return userList;
    }
}
